package com.zy.stock.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zy.stock.domain.User;
import com.zy.stock.service.UserService;
import com.zy.stock.util.PrincipalCollectionPool;

//import com.stormlions.ecost.domain.User;
//import com.stormlions.ecost.service.LoginService;
//import com.stormlions.ecost.util.PrincipalCollectionPool;

/**
 * 用户登录权限校验
 * */
@Component("stockRealm")
public class StockRealm extends AuthorizingRealm {

	private Logger logger = LoggerFactory.getLogger(StockRealm.class);

	@Autowired
	private UserService userService;
	
	/**
	 * 为当前登录的Subject授予角色和权限
	 * 大致流程获取当前角色从验证方法doGetAuthenticationInfo获取username获取角色名
	 * 将结果进行缓存，如果不增加ecache每次校验都会进行授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
		String currentUsername = (String) super.getAvailablePrincipal(principals);
		// 将当前用户写入全局map
		PrincipalCollectionPool.setPrincipalCollection(currentUsername,principals);
		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		// 为当前用户设置角色和权限
		User user = null;
		try{
			if(currentUsername != null){
				user = userService.findByName(currentUsername);
				if(user != null && (user.getName().equalsIgnoreCase("yubo")||user.getName().equalsIgnoreCase("zhangyi"))){
					simpleAuthorInfo.addRole("admin");
					simpleAuthorInfo.addStringPermission("admin:view");
					//simpleAuthorInfo.addStringPermission("admin:manage");
					return simpleAuthorInfo;
				}
			}
		}catch(Exception e){
			logger.error(e.toString());
			return simpleAuthorInfo;
		}
		return simpleAuthorInfo;
	}

	/**
	 * 验证当前登录的Subject
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = null;
		try {
			user = userService.findByName(token.getUsername());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (token.getUsername() != null && user != null) {
			AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassword(), user.getAlias());
			setSession(user);
			logger.info("user " + user.getName() + " valication success");
			return authcInfo;
		} else {
			logger.warn("not found username = " + token.getUsername());
			return null;
		}
	}

	/**
	 * 设置当前用户session
	 * */
	private void setSession(User user) {
		Subject currentUser = SecurityUtils.getSubject();
		if (null != currentUser) {
			Session session = currentUser.getSession();
			if (null != session) {
				session.setAttribute("sessionid", session.getId());
				session.setAttribute("id", user.getId());
				session.setAttribute("user_alias", user.getAlias());
				session.setAttribute("username", user.getName());
				session.setAttribute("user_email", user.getEmail());
				session.setAttribute("user_phone", user.getPhone());
				session.setAttribute("login_time", System.currentTimeMillis() / 1000);
			}
		}
	}
}
